App.controller('bidController', ['$rootScope','$timeout', '$scope', '$state', 'Page', function ($rootScope,$timeout, $scope, $state, Page) {

	//引入界面js
	Page.ajaxPostQuiet('biddingDeposit/queryCustomerList.do', null, function (resp) {
        $scope.customerList = resp.data;
	});
	
	Page.ajaxPostQuiet('media/bus/companys.do', null, function (resp) {
    	  $scope.companys = resp.data;
    });
	
	/*Page.ajaxPostQuiet('biddingDeposit/queryBidList.do', null, function (resp) {
        $scope.bidList = resp.data;
	});*/
	
    $scope.biddingDepositGrid = {
    		options : {
				lazy : true
			},
        column_defs: [
                      {
                          target: 5,
                          buttons: [
                              {
                                  name: '修改',
                                  class: 'btn-edit',
                                  icon: 'fa-wrench',
                                  event: 'update',
                                  visiable: function(row) {
                                    	if(row.depositSource=='1'){// 手动录入
                                    		 return true;
                                    	}else {// 缴费记录不允许删除
                                    		 return false;
                                    	}
                                    }
                              },
                              {
                                  name: '删除',
                                  class: 'btn btn-danger',
                                  icon: 'fa-trash-o',
                                  event: 'deleteDeposit',
                                  visiable: function(row) {
                                  	if(row.depositSource=='1'){// 手动录入
                                  		 return true;
                                  	}else {// 缴费记录不允许删除
                                  		 return false;
                                  	}
                                  }
                              }
                          ]
                      }
        ],
        add : function() {
            $scope.biddingDeposit = {};
            $scope.addFlag = true;
            $scope.biddingDepositAddModal.show();
        },
        update : function(row) {
            $scope.biddingDeposit = row;
            $scope.addFlag = false;
            $scope.biddingDepositAddModal.show();
        },
        deleteDeposit : function(row) {
            Page.confirm("确定要删除该保证金记录吗？", function () {
                Page.ajaxPost('biddingDeposit/delete.do', row, function () {
                    $scope.biddingDepositGrid.query();
                });
            });
        }
    };
    
    $scope.biddingDepositAddModal = {
	     onOkClick : function() {
	    	 $scope.$$prevSibling.$$nextSibling.$$childTail.biddingDepositForm.doValidate();
	       	 if( $scope.$$prevSibling.$$nextSibling.$$childTail.biddingDepositForm.$valid) {
       		 if($scope.addFlag) { //添加
        			url = "biddingDeposit/add.do";
    		 }else {
        			url = "biddingDeposit/update.do";
    		 }
       		$scope.biddingDeposit.bidId = $scope.bidId;
        	 Page.ajaxPost(url, $scope.biddingDeposit, function (resp) {
        		 $scope.biddingDepositAddModal.hide();
        		 Page.notice("信息保存成功");
        		 $scope.biddingDepositGrid.query();
            }); 
	       }
	     },
	     customerChange : function() {// 选择客户
	    	 $scope.biddingDeposit.bidId = $scope.bidId;
	    	 Page.ajaxPost('biddingDeposit/getCustomerDeposit.do', $scope.biddingDeposit, function (resp) {
    			 $scope.dataArray = resp.data.dataArray;
    			 if(resp.data.dataArray.length>0){// 已经交过保证金 不允许重复提交
						Page.notice("【"+resp.data.customerName+"】 已提交过保证金!请勿重复提交!");
						$('#deposit').attr("disabled",true);
					}else {
						$('#deposit').attr("disabled",false);
					}
            }); 
	     },
	     onHidden : function() {
    	}
       }
	
	
	
    $scope.treeSetting = { check: { enable: true,chkDisabledInherit: true }, data: { simpleData: { enable: true } } };
    $scope.scheduleQuery = {};
    $scope.resourceQuery = {};
    $scope.resourceInfo = {};
    $scope.bidRecordGrid = {
    		options : {
				lazy : true
			}
    }
    
    $scope.bidGrid = {

        column_defs: [
            {
        	    target: 2,
                template: function(row) {
                	if(row.status == 0){// 未发布
                		 return row.bidTitle;
                	}else {
                		 return row.bidTitle;
                	 }
                   }
                 },
            {
                target: 6,
                buttons: [
                    {
                        name: '配置',
                        class: 'btn-edit',
                        icon: 'fa-wrench',
                        event: 'update',
                        visiable: function(row) {
                        	return true;
                        }
                    },
                    {
                        name: '竞价明细',
                        class: 'btn-edit',
                        icon: 'fa-wrench',
                        event: 'viewRecord',
                        visiable: function(row) {
                        	if(row.status!='0'){// 未发布或者竞价中
                        		 return true;
                        	}else {
                        		 return false;
                        	}
                        }
                    },
                    {
                        name: '保证金',
                        class: 'btn btn-warning',
                        icon: 'fa-money',
                        event: 'manageDeposit',
                        visiable: function(row) {
                        	if(row.status!='0'){// 未发布或者竞价中
                        		 return true;
                        	}else {
                        		 return false;
                        	}
                        }
                    },
                    {
                        name: '删除',
                        class: 'btn btn-danger',
                        icon: 'fa-trash-o',
                        event: 'deleteBid',
                        visiable: function(row) {
                        	if(row.status=='0'){// 未发布
                        		 return true;
                        	}else {
                        		 return false;
                        	}
                        }
                    },
                    {
                        name: '发布',
                        class: 'btn blue',
                        icon: 'fa-arrow-up',
                        event: 'publishBid',
                        visiable: function(row) {
                        	if(row.status=='0'){// 未发布
                        		 return true;
                        	}else {
                        		 return false;
                        	}
                        }
                    }
                ]
            }
        ],
        add : function() {
            $scope.bid = {};
            $scope.bidId = "";
            $scope.bidAddFlag = true;
            $scope.showTitle = "";
            $scope.mediaTypes=[];
            $scope.media = null;// 重新初始化
            $scope.bidAddModal.show();
            $scope.bidTotalMoney = "0";
            $scope.status='0';
            $scope.disabledFlag = false;
            $scope.bidEndFlag = false;

            /*$(".tab-content .portlet-title").find('button').each(function(index, button) {
				 if ($(this).hasClass('disabled')) {
					 $(this).removeClass('disabled');
					 $(this).removeAttr('title');
					 $scope.disabledFlag = false;
              }
		     }) */
        },
        update : function(row) {
        	$scope.bid = row;
        	
        	$scope.bid.basePrice = $scope.bid.basePrice + ".00";
        	$scope.bid.increasePrice = $scope.bid.increasePrice + ".00";
        	$scope.bid.deposit = $scope.bid.deposit + ".00";
        	$scope.bid.winningPrice = $scope.bid.winningPrice + ".00";
        	
        	$scope.bidAddFlag = false;
        	$scope.bidId = $scope.bid.bidId;
            $scope.status = $scope.bid.status;
            $scope.showTitle = " -- "+$scope.bid.bidTitle;
            $scope.media = null;// 重新初始化
            //查询竞价包含的资源类型
            var param = {};
			param.bidId = $scope.bid.bidId;
			Page.ajaxPost('bid/getBidResourceGroupByTypes.do', param, function (resp) {
				$scope.mediaTypes = resp.data.array;
				//计算竞价单总金额
				$scope.resourceInfoOfAddModal.countTotalMoney();
				if($scope.status=='0'){// 未发布才能选择资源
					 $scope.disabledFlag = false;
				 }else {
					 $scope.disabledFlag = true;
			   }
				if($scope.status=='2'){// 竞价结束
					$scope.bidEndFlag = true;
				}else {
					$scope.bidEndFlag = false;
				}
				$scope.bidAddModal.show();
			}); 
        },
        viewRecord : function(row) {
        	$scope.bidId = row.bidId;
        	$scope.bidTitle = row.bidTitle;
        	$scope.bidRecordModal.showBidRecord();
        },
        publishBid : function(row) {
        	$scope.bidTitle =  row.bidTitle;
        	$scope.bidId = row.bidId;
        	$scope.publishInfoModal.showPublishInfo(row)
        },
        viewResourceSchedule : function(resource,parentId) {// 显示资源排期情况
        	$scope.billResourceScheduleModal.show();
        	$scope.resourceParentType = parentId;
        	$scope.query(resource.resourceId);
        },
        deleteBid : function(row) {
            Page.confirm("确定要删除吗？", function () {
                Page.ajaxPost('bid/delete.do', row, function () {
                	 $scope.bidGrid.query();
                });
            });
        },
        deleteResource : function(resource) {
        	 for (var i = 0; i < $scope.mediaTypes.length; i++) {
        		 for (var j = 0; j < $scope.mediaTypes[i].resources.length; j++) {
            		 if($scope.mediaTypes[i].resources[j].resourceId==resource.resourceId){
            			 $scope.mediaTypes[i].resources.splice(j,1);
            		 }
        		 }
        	 }
        	//计算竞价单总金额
			 $scope.resourceInfoOfAddModal.countTotalMoney();
         },
         manageDeposit :function(row) {
        	$scope.bidTitle =  row.bidTitle;
        	$scope.bidId =  row.bidId;
        	$scope.depositModal.show();
        	$scope.biddingDepositGrid.query.bidId = row.bidId;
        	$scope.biddingDepositGrid.query();
        }
    }
    
    $scope.publishInfoModal = {
			onShow : function(){
				this.setTitle('发布竞价单-- ' +$scope.bidTitle);
			},
			showPublishInfo : function() {
	            $scope.publishInfoModal.show();
		     },
		     onOkClick : function() {
		    	 $scope.publishInfoForm.doValidate();
    	       	 if($scope.publishInfoForm.$valid) {
		    	 if($scope.publishInfo.days == null || $scope.publishInfo.days ==''){
		    		 Page.notice("请填写发布期限!");
		    		 return false;
		    	 }
		    	 var param = {};
		    	 param.bidId = $scope.bidId;
		    	 param.days = $scope.publishInfo.days;
	        	 Page.ajaxPost('bid/publishBid.do', param, function () {
	        		 $scope.publishInfoModal.hide();
	        		 $scope.publishInfo.days = "";
	            	 $scope.bidGrid.query();
	            }); 
		       }
		     },
		     onHidden : function() {
        	},
	}
    
    $scope.bidRecordModal = {
			onShow : function(){
				this.setTitle('竞价记录-- ' +$scope.bidTitle);
			},
			showBidRecord : function() {
				$scope.bidRecordGrid.query.bidId = $scope.bidId;
				$scope.bidRecordGrid.query();
	            $scope.bidRecordModal.show();
		     }
	}

    $scope.resourceTree = {
    		addBidResource : function(){//添加车辆资源信息
    			this.clearValue();
    			if($scope.status=='0'|| typeof($scope.status) == "undefined"){// 未发布才能选择资源
    				$scope.resourceOfAddModal.show();
    				if($scope.media==null && $scope.mediaTypes.length>0){// 没有点击tab，默认是第一个
    					$scope.media = $scope.mediaTypes[0];
    				}
    				$scope.resourceQuery.resourceParentType = $scope.media==null?"":$scope.media.parentId;
    				this.parentTypeChange($scope.resourceQuery.resourceParentType);
    				$scope.resourceQuery.resourceType = $scope.media==null?"":$scope.media.mediaId;
                	$scope.resourceQuery.companyId = "1";//默认一分公司
                	//this.showTreeByResourceType();
    			}
            },
            
            clearValue : function(){// 清除值
            	$scope.resourceQuery.lineName = "";
    			$scope.resourceQuery.stopName = ""; 
    			$scope.resourceInfo.resourcePrice = "";
	   			$scope.resourceInfo.startDate = "";
	   			$scope.resourceInfo.endDate = "";
	   			$("#lineDiv").hide();
				$("#stopDiv").hide();
            },
            
            showTreeByResourceType : function(){// 根据类型、分公司查询数据
            	var resourceType = $scope.resourceQuery.resourceType;
            	var companyId = $scope.resourceQuery.companyId;
            	var resourceParentType = $scope.resourceQuery.resourceParentType;
            	if(resourceType==null || resourceType==''){
            		Page.notice("请选择具体的资源类型");
            		$.fn.zTree.init($("#treeOfResource"), $scope.treeSetting, []);
            		return false;
            	}
            	if(resourceParentType=='1' && (companyId==null || companyId == '')){
            		Page.notice("请选择车辆营运公司");
            		$.fn.zTree.init($("#treeOfResource"), $scope.treeSetting, []);
            		return false;	
            	}
	        	var param = {};
	        	var url = '';
	      		param.bidId = $scope.bidId;
	      		param.resourceType = resourceType;
	      		param.companyId = companyId; 
	      		if (resourceParentType=='1') {// 车辆
	      			url = 'bid/getResourceOfBusTree.do';
	      			param.lineName = $scope.resourceQuery.lineName;
	      		} else {// 站点
	      			url = 'bid/getResourceOfStopTree.do';
	      			param.stopName = $scope.resourceQuery.stopName;
	      		}
	      		Page.ajaxPost(url, param, function (resp) {
	      			var zNodes = resp.data.array;
	      			/*for (var i = 0; i < $scope.mediaTypes.length; i++) {
	      				if($scope.mediaTypes[i].mediaId == resourceType){
      					 for (var k = 0; k < zNodes.length; k++) {
	      					 for (var j = 0; j < $scope.mediaTypes[i].resources.length; j++) {
	    	           				if($scope.mediaTypes[i].resources[j].resourceId==zNodes[k].id ){// 将竞价单暂时全部的资源都回显选中
	    	           					zNodes[k].checked = true;
	    	           					zNodes[k].open = true;
	    	           					break;
	    		               		 }
	    	           			 }
	    	           		 }
	      				}
	           	 }*/
	      			var nodeSize = zNodes.length;
	      			for (var i = 0; i < $scope.mediaTypes.length; i++) {
	      				if($scope.mediaTypes[i].mediaId == resourceType){
	      					 for (var j = 0; j < $scope.mediaTypes[i].resources.length; j++) {
	      						 for (var k = 0; k < nodeSize; k++) {
		    	           				if($scope.mediaTypes[i].resources[j].resourceId==zNodes[k].id ){// 将竞价单暂时全部的资源都删掉，不让勾选
		    	           					zNodes[k].chkDisabled = true;
		    	           					break;
		    		               		 }
	      							 }
	      						 }
	      					 }
	      				}
	      			//todo 子节点选中后，也选中父节点
          		$.fn.zTree.init($("#treeOfResource"), $scope.treeSetting, zNodes);
			 }); 
            },
            conditionChange : function(){
            	var resourceType = $scope.resourceQuery.resourceType;
            	var companyId = $scope.resourceQuery.companyId;
            	var resourceParentType = $scope.resourceQuery.resourceParentType;
            	if(resourceParentType=='1' && (companyId==null || companyId == '')){
            		$.fn.zTree.init($("#treeOfResource"), $scope.treeSetting, []);
            	}else {
            		this.showTreeByResourceType();
            	}
            },
            //级联查询二级类型
        	parentTypeChange : function(resourceParentType) {
        		var param = {};
        		var parentId = resourceParentType;
        		$scope.resourceQuery.companyId="";
        		$scope.resourceQuery.resourceType= "";
        		$.fn.zTree.init($("#treeOfResource"), $scope.treeSetting, []);// 清空树
        		if(parentId==''){
        			$scope.resourceTypes=[];
        			$("#companySelect").hide();
        		}else {
        			param.parentId = parentId;
        			Page.ajaxPost('mediaType/getMediaTypesByParentId.do', param, function(resp) {
        				$scope.scheduleQuery.resourceType="";
        				$scope.resourceTypes=resp.data;
        				if(parentId=='1'){
        					$("#companySelect").show();
        					$("#lineDiv").show();
        					$("#stopDiv").hide();
        				}else {
        					$("#stopDiv").show();
        					$("#companySelect").hide();
        					$("#lineDiv").hide();
        				}
        			});
        		}
        	}
    }

    
    $scope.bidAddModal = {
    		onShow : function(){
    			this.setTitle('竞价记录'+$scope.showTitle);

				//去除第二个tab的选中样式
				$("#basicInfo").next().removeClass("active");
				$timeout(function(){
					//tab默认选中第一个
					$("#basicInfo").addClass("active");
					$("#basicInfo").find("a").click();
				},10);
       		},
       		onOkClick : function() {
   			 var url = "";
       		 if($scope.bidAddFlag) { //添加
       			url = "bid/add.do";
       		 }else {
       			url = "bid/update.do";
       		 }
       		 if($scope.status=='0'){

				 if(!$scope.$$childHead.tabs[0].$parent.bidForm.$valid) {
					 !$scope.$$childHead.tabs[0].$parent.bidForm.doValidate();
					 return;
				 }

       			 if(!this.doValidateForm($scope.bid)){
       				 Page.notice("订单基本信息未填写完整!");
       				 return false;
       			 }
       			Page.ajaxPost(url, $scope.bid, function (resp) {
	       			var bidId = resp.data.bidId;
				  //保存竞价资源信息
		       		var param = {};
		        	var resourceDatas = [];
		        	var allResources = $scope.mediaTypes;
		        	  for (var i = 0; i < allResources.length; i++) {
		        		  for (var j = 0; j < allResources[i].resources.length; j++) {
		        			  allResources[i].resources[j].bidId = bidId;
		        			  resourceDatas.push(allResources[i].resources[j]);  
		        		 }
		        	  }
		        		 param.bidId = bidId;
		        		 param.resourceDatas = resourceDatas;
		    	    	 Page.ajaxPost('bid/addResourceOfBill.do', param, function (resp) {
		        	    		 $scope.bidAddModal.hide();
		        	    		 Page.notice("竞价信息保存成功!");
		        	    		 $scope.bidGrid.query();
		        	 	});  
				});   
       		 }else {// 已发布的信息不能修改
       			 $scope.bidAddModal.hide(); 
       		 		}
        	},
        	doValidateForm : function(bid){
	        		if (typeof (bid.bidCode) == 'undefined'
							|| typeof (bid.bidTitle) == 'undefined'
							|| typeof (bid.deposit) == 'undefined'
							|| typeof (bid.basePrice) == 'undefined'
							|| typeof (bid.increasePrice) == 'undefined') {
									return false;
								} else {
									return true;
								}
        	},
        	onHidden : function() {
            	//$scope.bidForm.reset();
        	}
    	};
    

    //新增用户确定按钮
    bidAddTrue = function() {
        if(!$scope.validateForm.$valid) {
            $scope.validateForm.doValidate();
        } else {
            $scope.bidAddModal.hide();
        }
    }

    //新增用户取消按钮
    bidAddCancel = function() {
        $scope.validateForm.reset();
    }

    //查看资源确定
    bidViewTrue = function() {

    }
    //查看资源取消
    bidViewCancel = function() {

    }

    
    bidResourceTrue = function() {
    
    }

    bidResourceCancel = function() {

    }

    bidRecordTrue = function() {

    }

    bidRecordCancel = function() {

    }
    
    //保存选中资源
    resourceOfAddTrue = function () {
    	var treeObj = $.fn.zTree.getZTreeObj("treeOfResource");
		var nodes=treeObj.getCheckedNodes(true);// 获取当前被勾选的节点集合
	    var resourceIds = "";
	    var leafNodes = [];
	    for (var i = 0; i < nodes.length; i++) { 
		   if(!nodes[i].isParent){
			   leafNodes.push(nodes[i]);
		   }
	    }
	    var resourceType = $scope.resourceQuery.resourceType;
     	var resourceParentType = $scope.resourceQuery.resourceParentType;
	   if(leafNodes.length==0){
			/* // Page.notice("请选择具体的资源!"); 
	      	for(var j = 0; j < $scope.mediaTypes.length; j++){
	      		if($scope.mediaTypes[j].mediaId == resourceType ){// 删除了某种类型的全部资源
	      			$scope.mediaTypes.splice(j,1);
	      		}
	      	}
	    	//计算竞价单总金额
	      	 $scope.resourceInfoOfAddModal.countTotalMoney();*/
	      	 $scope.resourceOfAddModal.hide();  
	   }else {
		   var nodesData = $scope.resourceInfoOfAddModal.getWantAddNodes(leafNodes);// 存新增节点
		   if(nodesData.length>0){// 存在新增节点
			    $scope.resourceInfoOfAddModal.show();    
		   }/*else {// 不存在新增节点
			   // 删除去掉的节点
			   var hasResources = [];// 某种类型的资源
			   for (var m = 0; m < $scope.mediaTypes.length; m++) {
		    		if($scope.mediaTypes[m].mediaId ==resourceType){
		    			for (var j = 0; j < $scope.mediaTypes[m].resources.length; j++) {
		    				var res = {};
		    				res.resourceId = $scope.mediaTypes[m].resources[j].resourceId;
		    				res.isDel = true;
		    				hasResources.push(res);
		    			}
		    		}
		    	}
			   for (var i = 0; i < hasResources.length; i++) {
	    			 for (var j = 0; j < leafNodes.length; j++) {
  					 if(hasResources[i].resourceId ==leafNodes[j].id){// 记录存在
  						hasResources[i].isDel = false;
  						 break;
	             		 }
	         		 }	
          	 }
			   for (var m = 0; m < hasResources.length; m++) {
				   if(hasResources[m].isDel){
					   $scope.bidGrid.deleteResource(hasResources[m]);
				   }
			   }
			   $scope.resourceOfAddModal.hide();   
		   }*/
	   }
    }
    
    resourceOfAddCancel = function () {}
    
     $scope.resourceInfoOfAddModal = {
    		 nodeChcheDataArray : [],// 缓存选中过的资源节点
    		 onOkClick : function () {
    		    	$scope.resourceInfoForm.doValidate();
    		       	if($scope.resourceInfoForm.$valid) {
    		        	var treeObj = $.fn.zTree.getZTreeObj("treeOfResource");
    		    		var nodes=treeObj.getCheckedNodes(true);// 获取当前被勾选的节点集合
    		    	    var resourceIds = "";
    		    	    var leafNodes = [];
    		        	//只获取叶子节点
    		    	   for (var i = 0; i < nodes.length; i++) { 
    		    		   if(!nodes[i].isParent){
    		    			   leafNodes.push(nodes[i]);
    		    		   }
    		    	   }
    		    	   if($scope.resourceInfo.startDate >= $scope.resourceInfo.endDate) {
	   	                    Page.notice("开始时间不能大于或等于截止时间!");
	   	                    return;
   	                	}
    		    	   // 校验资源时间 
    		    	    var nodesData = $scope.resourceInfoOfAddModal.getWantAddNodes(leafNodes);
    			    	var param = {};
    			    	param.bidId = $scope.bidId;
    			    	param.nodesData = nodesData;
    			    	Page.ajaxPost('bid/verifyResourceDate.do', param, function (resp) {
    			    		var datas = resp.data.resIdToEndDateArray;
    			    		var startDate = $scope.resourceInfo.startDate;
    			    		for (var i = 0; i < datas.length; i++) {
    			    			if(startDate<=datas[i].endDate){// 所选开始时间小于等于资源所占用的最大日期
    			    				Page.notice("【"+datas[i].resourceName+"】所选开始时间必须大于"+datas[i].endDate);
    			    				return false;
    			    			}
    			    		}
    			    		
			    		// 缓存选中过的资源节点
    			    		$scope.resourceInfoOfAddModal.getNodeChcheDataArray(leafNodes);
	    				    $scope.resourceInfoOfAddModal.hide();
	    					$scope.resourceOfAddModal.hide();
	    					var param = {};
	    					param.bidId = $scope.bidId;
    						var flag = true;
    						
    						
    						if($scope.mediaTypes.length==0){//全部资源为新增
    							//$scope.mediaTypes = $scope.resourceInfoOfAddModal.nodeChcheDataArray;
    							$scope.mediaTypes.push($scope.resourceInfoOfAddModal.nodeChcheDataArray)
    						}else {
    							for(var i = 0; i < $scope.mediaTypes.length; i++){
    								if($scope.mediaTypes[i].mediaId == $scope.resourceInfoOfAddModal.nodeChcheDataArray.mediaId){
    									$scope.mediaTypes[i].resources.push.apply($scope.mediaTypes[i].resources,$scope.resourceInfoOfAddModal.nodeChcheDataArray.resources);// 追加选择的资源
									    break;
    								}else {
										$scope.mediaTypes.push($scope.resourceInfoOfAddModal.nodeChcheDataArray);
										break;
									}
    							}
    						}
    						
    						
    					/*	
    						for(var j = 0; j < $scope.resourceInfoOfAddModal.nodeChcheDataArray.length; j++){
    							for(var i = 0; i < $scope.mediaTypes.length; i++){
    								if($scope.mediaTypes[i].mediaId==$scope.resourceInfoOfAddModal.nodeChcheDataArray[j].mediaId){
    									$scope.mediaTypes[i].resources=$scope.resourceInfoOfAddModal.nodeChcheDataArray[j].resources;// 资源覆盖
    		    						$scope.resourceInfoOfAddModal.nodeChcheDataArray[j].flag = true;
    		    						break;
    		    					} 
    							}
    						}
    						if($scope.mediaTypes.length==0){//全部资源为新增
    							$scope.mediaTypes = $scope.resourceInfoOfAddModal.nodeChcheDataArray;
    						}else {
    							for(var k = 0; k < $scope.resourceInfoOfAddModal.nodeChcheDataArray.length; k++){
    								if(!$scope.resourceInfoOfAddModal.nodeChcheDataArray[k].flag){// 新增某一种类型资源
    									$scope.mediaTypes.push($scope.resourceInfoOfAddModal.nodeChcheDataArray[k]);
    								}
    							}
    						}*/
    						//计算竞价单总金额
    						 $scope.resourceInfoOfAddModal.countTotalMoney();
    					 });
    		       	}
    		    },
		     getNodeChcheDataArray : function(leafNodes) {
		    	this.nodeChcheDataArray = {};
		     	var selectNodesArray = [];
		  	    var nodeData = {};
		  	    nodeData.mediaId = $scope.resourceQuery.resourceType;
		  	    nodeData.parentId = $scope.resourceQuery.resourceParentType;
		  	    nodeData.flag = false;
		  	    //处理选中的节点
		  	    for (var i = 0; i < leafNodes.length; i++) { 
		  	    	nodeData.mediaName = leafNodes[i].mediaName;
		  	    	var node = {};
		  	    	node.resourceId = leafNodes[i].id;
		  	    	node.resourceName = leafNodes[i].name;
		  	    	node.plateNo = leafNodes[i].plateNo;
		  	    	node.lineNo = leafNodes[i].lineNo;
		  	    	node.stopName = leafNodes[i].stopName;
		  	    	node.roadName = leafNodes[i].roadName;
		  	    	node.resourcePrice = $scope.resourceInfo.resourcePrice;
		  	    	node.startDate = $scope.resourceInfo.startDate;
		  	    	node.endDate = $scope.resourceInfo.endDate;
		  	    	/*for (var m = 0; m < $scope.mediaTypes.length; m++) {
		         		 for (var n = 0; n < $scope.mediaTypes[m].resources.length; n++) {
		             		 if($scope.mediaTypes[m].resources[n].resourceId==node.resourceId){// 原记录存在,不赋值时间、价格
		             			node.resourcePrice = $scope.mediaTypes[m].resources[n].resourcePrice;
		             			node.startDate = $scope.mediaTypes[m].resources[n].startDate;
		             			node.endDate = $scope.mediaTypes[m].resources[n].endDate;
		             		 }
		         		 }
		         	 }*/
		  	    	selectNodesArray.push(node);
		   	   }
		  	    nodeData.resources = selectNodesArray;
		  	   /* for(var i = 0; i < this.nodeChcheDataArray.length; i++){// 同一类型资源数据覆盖
		  	    	if(this.nodeChcheDataArray[i].mediaId==nodeData.mediaId){
		  	    		this.nodeChcheDataArray.splice(i,1);
		  	    	}
		  	    }*/
		  	  this.nodeChcheDataArray = nodeData;
		    },
		    getWantAddNodes : function(leafNodes){// 得到待增加的节点
		    	
		    	var nodesArray = [];//用于下面节点的校验
		    	for (var i = 0; i < leafNodes.length; i++) { 
	 			   var node = {};
	 			   node.resourceId = leafNodes[i].id;
	 			   //node.isAdd = true;//用于下面节点的校验
	 			   nodesArray.push(node);
		 	   }
		    	/*var nodesData = [];
			    var hasResources = [];
		    	var mediaId = $scope.resourceQuery.resourceType;
		    	var parentId = $scope.resourceQuery.resourceParentType;
		    	for (var m = 0; m < $scope.mediaTypes.length; m++) {
		    		if($scope.mediaTypes[m].mediaId ==mediaId){
		    			hasResources = $scope.mediaTypes[m].resources;
		    		}
		    	}
		    	if(hasResources.length>0){
		    		for (var k = 0; k < nodesArray.length; k++) {
	    	    			 for (var n = 0; n < hasResources.length; n++) {
		    					 if(nodesArray[k].resourceId ==hasResources[n].resourceId){// 原记录存在
		    						 nodesArray[k].isAdd = false;
		    						 break;
			             		 }
	    	         		 }	
		            	 }
		    		for (var k = 0; k < nodesArray.length; k++) {
		    			if(nodesArray[k].isAdd){// 原记录不存在（新增节点）
		    				nodesData.push(nodesArray[k]);
		    			}
		    		  }
		    		}else {// 全部节点新增
		    			nodesData = nodesArray;
		    	}*/
		    	return nodesArray;
		    },
		    countTotalMoney : function(){ // 重新计算竞价单总金额
   			 var bidTotalMoney = 0;
				 for(var m = 0; m < $scope.mediaTypes.length; m++){
					for(var n = 0; n < $scope.mediaTypes[m].resources.length; n++){
						if($scope.mediaTypes[m].resources[n].resourcePrice==''||$scope.mediaTypes[m].resources[n].resourcePrice ==null){
							bidTotalMoney +=0;
						}else {
							bidTotalMoney +=parseInt($scope.mediaTypes[m].resources[n].resourcePrice);
						}
					}
				}
				$scope.bidTotalMoney = bidTotalMoney;
	    	},
	   		clickTab : function(media){
	   			$scope.media = media;
	   		},
		     onHidden : function() {
	    	}
     }
    
    
     
     $scope.scheduleModal  = {};
     $scope.scheduleModal.month = "";
	  
    $scope.query = function(resourceId,lastOrNext, monthOrYear) {
		var param = {};
		param.month = $scope.scheduleModal.month;// 当前月份
		param.lastOrNext = lastOrNext;// -1：上一月 上一年 1：下一月 下一年
		param.monthOrYear = monthOrYear;// 1:年 2：月
		param.pageIndex = 0;
		param.pageSize = 15;
		param.resourceId = resourceId;
		param.resourceType = $scope.resourceParentType;//父类型
		Page.ajaxPost('schedule/query.do', param, function(resp) {
			$scope.months = resp.data.months;
			$scope.days = resp.data.daysArray;
			$scope.dataArray = resp.data.dataArray;
			$scope.lastYear = resp.data.lastYear;
			$scope.nextYear = resp.data.nextYear;
			$scope.totalPages = resp.data.totalPages;
			$scope.resourceId = resourceId;
			$scope.scheduleModal.month = resp.data.currentMonth;
		});
	}
	
  //选择月份
	$scope.monthChange = function(resourceId) {
		$scope.query(resourceId);
	}
	
	$scope.depositModal = {

    		onShow : function(){
    			this.setTitle('保证金 -- '+$scope.bidTitle);
       		},
       		onOkClick : function() {
       			$scope.depositModal.hide();
       		},
        	onHidden : function() {
        		$scope.depositModal.hide();
        	},
	}

}]);

